package down{
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	import flash.system.Security;
	/**
	 * 单个下载进程的下载管理
	 * @author 
	 */
	public class Download 
	{
		private var _url:String;
		private var _loader:URLLoader;
		private var _firstLoaded:Number = 0;//本次下载的大小
		private var _firstTotal:Number = 0;//上次下载到多少了
		private var _bytesTotal:Number = 0;//要下载的大小
		private var _bytesLoaded:Number = 0;//这次下载了多少
		
		public function Download(url:String):void{
			_url = url;
			_loader = new URLLoader();
		}
		public function start():void{
			Security.allowDomain("*");
			_bytesTotal = 0;
			_firstTotal = 0;
			_firstLoaded = 0;
			_bytesLoaded = 0;
			_loader.addEventListener(Event.COMPLETE, completeHandler);
            _loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            _loader.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			try {
				_loader.load(new URLRequest(_url + "?" + Math.random ()));
			} catch (error:Error) {
				//Main.traces("Unable to load requested document.");
			}
		}
		public function removeListeners():void{
            _loader.removeEventListener(Event.COMPLETE, completeHandler);
            _loader.removeEventListener(ProgressEvent.PROGRESS, progressHandler);
            _loader.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			_loader.close();
			_loader = null;
			_loader = new URLLoader();
        }
		public function get bytesLoaded():Number
		{
			return _bytesLoaded;
		}
		public function get bytesTotal():Number
		{
			return _bytesTotal;
		}
		public function get firstTotal():Number
		{
			return _firstTotal;
		}
		public function set firstTotal(value:Number):void
		{
			_firstTotal = value;
		}
		public function get firstLoaded():Number
		{
			return _firstLoaded;
		}
		public function set firstLoaded(value:Number):void
		{
			_firstLoaded=value;
		}
		private function completeHandler(e:Event):void 
		{
			removeListeners();
        }

        private function progressHandler(e:ProgressEvent):void 
		{	
			_bytesLoaded = e.bytesLoaded;
			_bytesTotal = e.bytesTotal;
        }

        private function ioErrorHandler(e:IOErrorEvent):void 
		{
			//Main.traces("ioErrorHandler");
        }
	}
}